package com.pig4cloud.pigx.common.security.grant.api;

import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * OpenApi令牌授予者
 *
 * @author hzq
 * @since 2021-09-14
 */
@Slf4j
public class ApiAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    /**
     * user 属性校验
     */
    @Setter
    private UserDetailsChecker preAuthenticationChecks = new AccountStatusUserDetailsChecker();

    /**
     * 校验传入的Token信息
     *
     * @param userDetails    用户信息
     * @param authentication token信息
     * @since 2022/11/7 17:55
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

		/*if (authentication.getCredentials() == null) {
			this.logger.debug("Failed to authenticate since no credentials provided");
			throw new BadCredentialsException(this.messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}*/

    }

    /**
     * 鉴权
     *
     * @param authentication token信息
     * @return {@link Authentication}
     * @since 2022/11/7 17:55
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        Object principal = authentication.getPrincipal();
        if (Objects.isNull(principal) || Strings.isBlank(principal.toString())) {
            log.debug("Failed to authenticate since no access key provided");
            throw new BadCredentialsException("Bad credentials");
        }

        ApiAuthenticationToken requestToken = (ApiAuthenticationToken) authentication;
        // 此处已获得 客户端认证 获取对应 userDetailsService
        Authentication clientAuthentication = SecurityContextHolder.getContext().getAuthentication();
        String clientId = clientAuthentication.getName();

        Map<String, PigxUserDetailsService> userDetailsServiceMap = SpringContextHolder
                .getBeansOfType(PigxUserDetailsService.class);
        Optional<PigxUserDetailsService> optional = userDetailsServiceMap.values().stream()
                .filter(service -> service.support(clientId, requestToken.getGrantType()))
                .max(Comparator.comparingInt(Ordered::getOrder));

        if (!optional.isPresent()) {
            throw new InternalAuthenticationServiceException("UserDetailsService error , not register");
        }

        // AccessKey
        String accessKey = principal.toString();
        UserDetails userDetails = optional.get().loadUserByUsername(accessKey);

        // userDeails 校验
        preAuthenticationChecks.check(userDetails);

        ApiAuthenticationToken token = new ApiAuthenticationToken(requestToken, userDetails);
        token.setDetails(authentication.getDetails());
        return token;

    }

    @Override
    protected UserDetails retrieveUser(String phone, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(ApiAuthenticationToken.class);
    }

}
